package cn.com.shadowless.xinning.view.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.mengpeng.mphelper.ToastUtils;

import java.util.List;

import butterknife.BindView;
import cn.com.shadowless.xinning.MyApplication;
import cn.com.shadowless.xinning.R;
import cn.com.shadowless.xinning.callback.RequestCallBack;
import cn.com.shadowless.xinning.model.RequestResult;
import cn.com.shadowless.xinning.model.order.CostOrderInfo;
import cn.com.shadowless.xinning.presenter.OrderPresenter;
import cn.com.shadowless.xinning.utils.PreferencesUtils;
import cn.com.shadowless.xinning.view.BaseFragment;

/**
 * The type Cost fragment.
 *
 * @author sHadowLess
 */
public class CostFragment extends BaseFragment {

    /**
     * The Cost receipt info receipt num.
     */
    @BindView(R.id.cost_receiptInfo_ReceiptNum)
    TextView costReceiptInfoReceiptNum;
    /**
     * The Cost receipt info make time.
     */
    @BindView(R.id.cost_receiptInfo_MakeTime)
    TextView costReceiptInfoMakeTime;
    /**
     * The Cost receipt info maker.
     */
    @BindView(R.id.cost_receiptInfo_Maker)
    TextView costReceiptInfoMaker;
    /**
     * The Cost receipt info making depart.
     */
    @BindView(R.id.cost_receiptInfo_MakingDepart)
    TextView costReceiptInfoMakingDepart;
    /**
     * The Cost receipt info position job.
     */
    @BindView(R.id.cost_receiptInfo_PositionJob)
    TextView costReceiptInfoPositionJob;
    /**
     * The Cost application proposer.
     */
    @BindView(R.id.cost_application_Proposer)
    TextView costApplicationProposer;
    /**
     * The Cost application propose depart.
     */
    @BindView(R.id.cost_application_ProposeDepart)
    TextView costApplicationProposeDepart;
    /**
     * The Cost application propose type.
     */
    @BindView(R.id.cost_application_ProposeType)
    TextView costApplicationProposeType;
    /**
     * The Cost application proposer reason.
     */
    @BindView(R.id.cost_application_ProposerReason)
    TextView costApplicationProposerReason;
    /**
     * The Cost single single reason.
     */
    @BindView(R.id.cost_single_SingleReason)
    TextView costSingleSingleReason;
    /**
     * The Cost single single amount.
     */
    @BindView(R.id.cost_single_SingleAmount)
    TextView costSingleSingleAmount;
    /**
     * The Cost single expected date.
     */
    @BindView(R.id.cost_single_ExpectedDate)
    TextView costSingleExpectedDate;
    /**
     * The Cost child tab info.
     */
    @BindView(R.id.cost_childTab_Info)
    LinearLayout costChildTabInfo;
    /**
     * The Cost check process.
     */
    @BindView(R.id.cost_check_Process)
    LinearLayout costCheckProcess;
    /**
     * The Cost temp item.
     */
    @BindView(R.id.cost_temp_item)
    LinearLayout costTempItem;

    private final String url = "api/ExpenseAppForm/LoadCheckHistory?%s=";
    private final String forMat = "%s公司预算金额：%s\n已报销：%s\n已申请未报销：%s\n报销中：%s\n在申请未报销：%s\n剩余可报销：%s\n剩余可申请：%s\n合计：%s";

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_cost_layout;
    }

    @Override
    protected void initData() {
        Bundle bundle = getArguments();
        if (null != bundle) {
            String orderId = bundle.getString("orderId");
            String userName = bundle.getString("userName");
            initCostOrderInfo(orderId, userName);
            initCheckHistoryList(String.format(url, "id") + orderId, mActivity, costCheckProcess);
        }
    }

    @Override
    protected void initView() {

    }

    private void initCostOrderInfo(String orderId, String userName) {
        OrderPresenter.getSingleton().getCostOrderInfo(orderId, userName, new RequestCallBack<CostOrderInfo>() {
            @Override
            public void success(RequestResult<CostOrderInfo> result) {
                String token = result.getLoginToken();
                String oldToken = PreferencesUtils.getString(MyApplication.getInstance(), "token", "-1");
                if (result.isSucceed() && null != result.getResult()) {
                    if (null != token && token.equals(oldToken)) {
                        Log.e(TAG, "success: " + result.toString());
                        CostOrderInfo.DataBean dataBean = result.getResult().getData();
                        CostOrderInfo.DataBean.CreateUserObjectBean userObjectBean = dataBean.getCreateUserObject();
                        List<CostOrderInfo.DataBean.ItemListBean> itemListBean = dataBean.getItemList();

                        String id = dataBean.getId();
                        String createTimeStr = dataBean.getCreateTimeStr();
                        String createUserName = dataBean.getCreateUserName();
                        String departmentName = dataBean.getDepartmentName();
                        String positionName = userObjectBean.getPositionName();
                        costReceiptInfoReceiptNum.setText(id);
                        costReceiptInfoMakeTime.setText(createTimeStr);
                        costReceiptInfoMaker.setText(createUserName);
                        costReceiptInfoMakingDepart.setText(departmentName);
                        costReceiptInfoPositionJob.setText(positionName);

                        String userName = userObjectBean.getUserName();
                        String departmentName1 = userObjectBean.getDepartmentName();
                        String duringTypeValue = dataBean.getDuringTypeValue();
                        String duringType = dataBean.getDuringType();
                        boolean isCompanyCost = dataBean.isCompanyCost();
                        boolean isTemp = dataBean.isTemp();
                        boolean isUrgent = dataBean.isUrgent();
                        String remark = dataBean.getRemark();
                        costApplicationProposer.setText(userName);
                        costApplicationProposeDepart.setText(departmentName1);
                        String type = duringTypeValue + duringType + "\n";
                        if (isCompanyCost) {
                            type = type + "√ 公司费用申请\n";
                        } else {
                            type = type + "X 公司费用申请\n";
                        }
                        if (isTemp) {
                            type = type + "√ 暂支\n";
                        } else {
                            type = type + "X 暂支\n";
                        }
                        if (isUrgent) {
                            type = type + "√ 紧急\n";
                        } else {
                            type = type + "X 紧急\n";
                        }
                        costApplicationProposeType.setText(type);
                        costApplicationProposerReason.setText(remark);

                        if (isTemp) {
                            costTempItem.setVisibility(View.VISIBLE);
                            String tempReason = dataBean.getTempReason();
                            String tempCost = getDecimal(dataBean.getTempCost().doubleValue());
                            String returnDateStr = dataBean.getReturnDateStr();
                            costSingleSingleReason.setText(tempReason);
                            costSingleSingleAmount.setText(tempCost);
                            costSingleExpectedDate.setText(returnDateStr);
                        } else {
                            costTempItem.setVisibility(View.GONE);
                        }

                        for (CostOrderInfo.DataBean.ItemListBean data : itemListBean) {
                            View view = LayoutInflater.from(mActivity).inflate(R.layout.fragment_cost_tab_item, null, false);
                            LinearLayout tabItem = view.findViewById(R.id.cost_tab_item);
                            TextView budget = view.findViewById(R.id.cost_tab_budget);
                            TextView originBudgetAmount = view.findViewById(R.id.cost_tab_originBudgetAmount);
                            TextView units = view.findViewById(R.id.cost_tab_Units);
                            TextView tabNum = view.findViewById(R.id.cost_tab_Num);
                            TextView tabPrice = view.findViewById(R.id.cost_tab_Price);
                            TextView applyAmount = view.findViewById(R.id.cost_tab_ApplyAmount);
                            TextView partial = view.findViewById(R.id.cost_tab_Partial);
                            TextView tabRemark = view.findViewById(R.id.cost_tab_Remark);
                            TextView budgetState = view.findViewById(R.id.cost_tab_BudgetState);

                            CostOrderInfo.DataBean.ItemListBean.BudgetTypeObjectBean budgetTypeObjectBean = data.getBudgetTypeObject();
                            CostOrderInfo.DataBean.ItemListBean.BudgetItemObjectBean budgetItemObjectBean = data.getBudgetItemObject();

                            String budgetTypeName = budgetTypeObjectBean.getBudgetTypeName();
                            String allMoney = getDecimal(budgetItemObjectBean.getAllMoney().doubleValue());
                            String unit = data.getUnit();
                            String num = data.getNum() + "";
                            String price = getDecimal(data.getPrice().doubleValue());
                            String currentBudget = getDecimal(data.getCurrentBudget().doubleValue());
                            boolean isBatches = data.isBatches();
                            if (isBatches) {
                                partial.setText("是");
                            } else {
                                partial.setText("否");
                            }
                            String itemRemark = data.getRemark();
                            String budgetInfo = budgetItemObjectBean.getBudgetInfo();
                            String reimbursedMoney = getDecimal(budgetItemObjectBean.getReimbursedMoney().doubleValue());
                            String applyedMoney = getDecimal(budgetItemObjectBean.getApplyedMoney().doubleValue());
                            String reimbursingMoney = getDecimal(budgetItemObjectBean.getReimbursingMoney().doubleValue());
                            String applyingMoney = getDecimal(budgetItemObjectBean.getApplyingMoney().doubleValue());
                            String remainReimburseMoney = getDecimal(budgetItemObjectBean.getRemainReimburseMoney().doubleValue());
                            String remainApplyMoney = getDecimal(budgetItemObjectBean.getRemainApplyMoney().doubleValue());
                            budget.setText(budgetTypeName);
                            originBudgetAmount.setText(allMoney);
                            units.setText(unit);
                            tabNum.setText(num);
                            tabPrice.setText(price);
                            applyAmount.setText(currentBudget);
                            tabRemark.setText(itemRemark);
                            budgetState.setText(String.format(
                                    forMat,
                                    budgetInfo,
                                    allMoney,
                                    reimbursedMoney,
                                    applyedMoney,
                                    reimbursingMoney,
                                    applyingMoney,
                                    remainReimburseMoney,
                                    remainApplyMoney,
                                    currentBudget
                            ));
                            costChildTabInfo.addView(tabItem);
                        }
                    } else {
                        ToastUtils.onErrorShowToast("登录态与服务器不一致");
                        initLogoutInfo(mActivity, userName);
                    }
                } else {
                    ToastUtils.onErrorShowToast("该订单暂无详细信息");
                }
            }

            @Override
            public void fail(String errorMsg) {
                ToastUtils.onErrorShowToast(errorMsg);
            }
        });
    }
}
